package com.dy.yunying.biz.service.raffle.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dy.yunying.api.entity.hongbao.HbGiftBag;
import com.dy.yunying.api.entity.raffle.RaffleExchangeStore;
import com.dy.yunying.api.enums.GiftTypeEnum;
import com.dy.yunying.api.req.raffle.RaffleExchangeStoreReq;
import com.dy.yunying.biz.dao.ads.raffle.RaffleExchangeStoreMapper;
import com.dy.yunying.biz.service.hongbao.HbGiftBagService;
import com.dy.yunying.biz.service.raffle.RaffleExchangeStoreService;
import com.dy.yunying.biz.service.sign.SignTaskConfigService;
import com.dy.yunying.biz.utils.DateUtils;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.security.util.SecurityUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 积分商店配置表服务接口实现
 *
 * @author zjz
 * @since 2022-11-07 18:36:03
 * @description 由 zjz 创建
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class RaffleExchangeStoreServiceImpl extends ServiceImpl<RaffleExchangeStoreMapper, RaffleExchangeStore> implements RaffleExchangeStoreService {
	private final HbGiftBagService hbGiftBagService;
	private final SignTaskConfigService signTaskConfigService;

	@Override
	public void saveBatchList(List<RaffleExchangeStore> list){
		this.saveBatch(list,1000);
	}

	@Override
	@Transactional(rollbackFor = Exception.class, transactionManager = "adsTransactionManager")
	public R createEdit(RaffleExchangeStoreReq req){
		RaffleExchangeStore raffleExchangeStore = new RaffleExchangeStore();
		BeanUtils.copyProperties(req, raffleExchangeStore);
		if(StringUtils.isNotBlank(req.getGiftStartTime())) {
			raffleExchangeStore.setGiftStartTime(DateUtils.stringToDate(req.getGiftStartTime(), DateUtils.YYYY_MM_DD_HH_MM_SS));
		}
		if(StringUtils.isNotBlank(req.getGiftEndTime())) {
			raffleExchangeStore.setGiftEndTime(DateUtils.stringToDate(req.getGiftEndTime(), DateUtils.YYYY_MM_DD_HH_MM_SS));
		}
		raffleExchangeStore.setUpdateId(Objects.requireNonNull(SecurityUtils.getUser()).getId().longValue());
		String info="操作成功";
		if(req.getId()!=null) {
			RaffleExchangeStore old = baseMapper.selectById(req.getId());
			if(old==null){
				return R.failed("不存在的积分商品ID");
			}
			if(GiftTypeEnum.COMMON.getType().equals(old.getGiftType())) {
				if (Objects.isNull(req.getGiftTotalNum())){
					req.setGiftTotalNum(0);
				}
				if(req.getGiftTotalNum() < old.getProductCostNum()){
					return R.failed("礼包码数量不能小于已领取数量");
				}
			}
			if ((req.getProductType() == 1||old.getProductType() == 1) && (!req.getProductType().equals(old.getProductType())  || !req.getGiftType().equals(old.getGiftType()))) {
				hbGiftBagService.getBaseMapper().delete(Wrappers.<HbGiftBag>lambdaQuery().in(HbGiftBag::getObjectId, req.getId()).eq(HbGiftBag::getType, 6));
				old.setProductInventory(-1);
			}
			if (req.getProductType().equals(NumberUtils.INTEGER_ONE) && GiftTypeEnum.COMMON.getType().equals(req.getGiftType())) {
				final HbGiftBag hbGiftBag = hbGiftBagService.getOne(Wrappers.<HbGiftBag>lambdaQuery()
						.eq(HbGiftBag::getType, 6)
						.eq(HbGiftBag::getObjectId, req.getId())
						.eq(HbGiftBag::getGiftCode, req.getGiftName())
						.last("limit 1"));
				if (Objects.isNull(hbGiftBag)) {
					HbGiftBag giftBag = new HbGiftBag();
					giftBag.setType(6);
					giftBag.setObjectId(req.getId());
					giftBag.setGiftCode(req.getGiftName());
					giftBag.setGiftAmount(req.getGiftTotalNum());
					giftBag.setUsable(2);
					giftBag.setCreateTime(new Date());
					giftBag.setUpdateTime(new Date());
					giftBag.setCreateId(Objects.requireNonNull(SecurityUtils.getUser()).getId().longValue());
					hbGiftBagService.save(giftBag);
				} else {
					HbGiftBag updateGift = new HbGiftBag();
					updateGift.setId(hbGiftBag.getId());
					updateGift.setGiftAmount(req.getGiftTotalNum());
					updateGift.setUpdateId(Objects.requireNonNull(SecurityUtils.getUser()).getId().longValue());
					updateGift.setDeleted(0);
					hbGiftBagService.updateById(updateGift);
				}
				raffleExchangeStore.setProductInventory(req.getGiftTotalNum());
			}
			if (GiftTypeEnum.UNIQUE.getType().equals(req.getGiftType()) && req.getFile() != null) {
				Pair<Integer, Integer> giftBag = signTaskConfigService.saveSignGiftBag(req.getFile(), 6, req.getId());
				info = "操作成功，礼包码上传成功：" + giftBag.getRight() + " 个，重复无效过滤：" + (giftBag.getLeft() - giftBag.getRight()) + " 个";
				Integer productInventory = old.getProductInventory() == -1 ? 0 : old.getProductInventory();
				raffleExchangeStore.setProductInventory(productInventory + giftBag.getRight());
			}
			this.baseMapper.updateById(raffleExchangeStore);
		}else {
			this.baseMapper.insert(raffleExchangeStore);
			if (GiftTypeEnum.COMMON.getType().equals(req.getGiftType())) {
				HbGiftBag giftBag = new HbGiftBag();
				giftBag.setType(6);
				giftBag.setObjectId(raffleExchangeStore.getId());
				giftBag.setGiftCode(req.getGiftName());
				giftBag.setGiftAmount(req.getGiftTotalNum());
				giftBag.setGiftGetcounts(0);
				giftBag.setUsable(2);
				giftBag.setCreateTime(new Date());
				giftBag.setUpdateTime(new Date());
				giftBag.setCreateId(Objects.requireNonNull(SecurityUtils.getUser()).getId().longValue());
				hbGiftBagService.save(giftBag);
				raffleExchangeStore.setProductInventory(req.getGiftTotalNum());
			}
			if (GiftTypeEnum.UNIQUE.getType().equals(req.getGiftType()) && req.getFile() != null) {
				Pair<Integer, Integer> giftBag = signTaskConfigService.saveSignGiftBag(req.getFile(), 6, raffleExchangeStore.getId());
				info = "操作成功，礼包码上传成功：" + giftBag.getRight() + " 个，重复无效过滤：" + (giftBag.getLeft() - giftBag.getRight()) + " 个";
				raffleExchangeStore.setProductInventory(giftBag.getRight());
			}
			this.baseMapper.updateById(raffleExchangeStore);
		}
		return R.ok(null,info);
	}

	@Override
	public R editOnPrize(RaffleExchangeStoreReq req){
		RaffleExchangeStore old = baseMapper.selectById(req.getId());
		String info="操作成功";
		if(old.getProductType()!=1){
			return R.failed("活动上线后只能追加礼包码");
		}
		if(!req.getGiftType().equals(old.getGiftType())){
			return R.failed("活动上线后礼包码类型不能修改");
		}
		if(GiftTypeEnum.COMMON.getType().equals(old.getGiftType())){
			if(req.getGiftTotalNum() < old.getProductCostNum()){
				return R.failed("礼包码数量不能小于已领取数量");
			}
			final HbGiftBag hbGiftBag = hbGiftBagService.getOne(Wrappers.<HbGiftBag>lambdaQuery()
					.eq(HbGiftBag::getType, 6)
					.eq(HbGiftBag::getObjectId, req.getId())
					.eq(HbGiftBag::getGiftCode, req.getGiftName())
					.last("limit 1"));
			if(Objects.isNull(hbGiftBag)) {
				HbGiftBag giftBag = new HbGiftBag();
				giftBag.setType(6);
				giftBag.setObjectId(req.getId());
				giftBag.setGiftCode(req.getGiftName());
				giftBag.setGiftAmount(req.getGiftTotalNum());
				giftBag.setUsable(2);
				giftBag.setCreateTime(new Date());
				giftBag.setUpdateTime(new Date());
				giftBag.setCreateId(Objects.requireNonNull(SecurityUtils.getUser()).getId().longValue());
				hbGiftBagService.save(giftBag);
			}else {
				HbGiftBag updateGift = new HbGiftBag();
				updateGift.setId(hbGiftBag.getId());
				updateGift.setGiftAmount(req.getGiftTotalNum());
				updateGift.setUpdateId(Objects.requireNonNull(SecurityUtils.getUser()).getId().longValue());
				updateGift.setDeleted(0);
				hbGiftBagService.updateById(updateGift);
			}
			old.setGiftTotalNum(req.getGiftTotalNum());
			old.setProductInventory(req.getGiftTotalNum());
		}
		if(GiftTypeEnum.UNIQUE.getType().equals(req.getGiftType())){

			if(req.getFile()!=null) {
				try {
					//校验礼包码文件并保存hb_gift_bag
					Pair<Integer, Integer> giftBag = signTaskConfigService.saveSignGiftBag(req.getFile(), 6, req.getId());
					info = "操作成功，礼包码上传成功：" + giftBag.getRight() + " 个，重复无效过滤：" + (giftBag.getLeft() - giftBag.getRight()) + " 个";
					old.setProductInventory(old.getProductInventory() + giftBag.getRight());
				} catch (IllegalArgumentException e) {
					return R.failed(e.getMessage());
				}
			}
		}
		this.updateById(old);
		return R.ok(null,info);
	}
}